<?php

namespace app\admin\controller;

use think\Db;
use think\Request;
use app\admin\model\Cotype;//公司类型
use app\admin\model\Coattr;//资料属性
use app\admin\model\Company;//资料属性
use app\admin\model\Linkman;//联系人
use app\admin\model\Co_bank;//银行
use app\admin\model\Co_branch;//分公司
use app\admin\model\Co_evaluate;//公司风评


class Customer extends Auth
{
    //公司类型
    public function customertype(Request $request)
    {
        $res = $request->param();
        if ($request->isAjax() && $request->isPost()) {
            //返回公司类型的数据
            $cotype = new Cotype();
            $getcotype = $cotype->getcotype($res);
            echo json_encode(array('getcotype' => $getcotype['data'], 'size' => $getcotype['count']));
        } elseif ($request->isGet()) {
            return view('cotype/cotype');
        }
    }

    //公司类型的添加
    public function cotypadd(Request $request)
    {
        $data = request()->param();
        $data['lang'] = $this->lang;
        $cotype = new Cotype();
        if ($request->isGet()) {
            return view('cotype/cotypeinfo', [
                'str' => 'cotypadd',
            ]);
        } elseif ($request->isAjax() && $request->isPost() && isset($data['getcotype'])) {
            $admin = session('admin');
            $admin_countryid = '';
            //不是全球管理员，返回这个职位的国家id
            if ($admin['position_id'] != 1) {
                $admin_countryid = getValue('position', ['id' => $admin['position_id']], 'country_id');
            }
            echo json_encode(array('info' => '', 'country_id' => $admin_countryid));
        } elseif ($request->isAjax() && $request->isPost() && $data['act'] == 'cotypadd') {
            $cotyperet = $cotype->addeditcotype($data);
            $udata["status"] = $cotyperet['status'];
            $udata['msg'] = $cotyperet['msg'];
            echo json_encode($udata);
        }
    }

    //公司类型的编辑
    public function cotypedit(Request $request)
    {
        $data = request()->param();
        $data['lang'] = $this->lang;
        $cotype = new Cotype();
        if ($request->isGet()) {
            return view('cotype/cotypeinfo', [
                'str' => 'cotypedit',
                'id' => $data['id'],
            ]);
        } elseif ($request->isAjax() && $request->isPost() && isset($data['getcotype'])) {
            $admin = session('admin');
            //获取对应的语言的公司类型
            $where['id'] = $data['id'];
            $info = getlanginfo('cotype', $where);
            $admin_countryid = '';
            //不是全球管理员，返回这个职位的国家id
            if ($admin['position_id'] != 1) {
                $admin_countryid = getValue('position', ['id' => $admin['position_id']], 'country_id');
            }
            echo json_encode(array('info' => $info, 'country_id' => $admin_countryid));
        } elseif ($request->isAjax() && $request->isPost() && $data['act'] == 'cotypedit') {
            $cotyperet = $cotype->addeditcotype($data);
            $udata["status"] = $cotyperet['status'];
            $udata['msg'] = $cotyperet['msg'];
            echo json_encode($udata);
        }

    }

    //公司类型的删除
    public function cotypdelete(Request $request)
    {
        $cotype = new Cotype();
        $data = $request->param();
        $data['lang'] = $this->lang;
        if ($request->isPost() && $request->isAjax()) {
            $cotyperet = $cotype->delcotype($data);
            $udata["status"] = $cotyperet['status'];
            $udata['msg'] = $cotyperet['msg'];
            echo json_encode($udata);
        }
    }

    //资料属性 （属性这里的国家是定死的两个)
    public function customercoattr(Request $request)
    {
        $res = $request->param();
        if ($request->isAjax() && $request->isPost()) {
            $coattr = new Coattr();
            $getcoattr = $coattr->getcoattr($res);
            echo json_encode(array('getcoattr' => $getcoattr['data'], 'size' => $getcoattr['count']));
        } elseif ($request->isGet()) {
            return view('coattr/coattr');
        }
    }

    //属性的添加
    public function coattradd(Request $request)
    {
        $data = request()->param();
        $coattr = new Coattr();
        $data['lang'] = $this->lang;
        if ($request->isGet()) {
            return view('coattr/coattrinfo', [
                'str' => 'coattradd',
            ]);
        } elseif ($request->isAjax() && $request->isPost() && isset($data['getcoattr'])) {
            //公司类型
            $where['a.lang'] = $data['langs'];//语言标志
            $join = [
                ['nt_cotype b', 'a.mkey=b.mkey']
            ];
            $table = 'multi_lang';
            //获取公司的类型
            $resdata = getmultidata($table, $join, $where)['data'];
            echo json_encode(array('info' => '', 'cotypedata' => $resdata));
        } elseif ($request->isAjax() && $request->isPost() && $data['act'] == 'coattradd') {
            $coattrret = $coattr->addeditcoattr($data);
            $udata["status"] = $coattrret['status'];
            $udata['msg'] = $coattrret['msg'];
            echo json_encode($udata);
        }

    }

    //资料属性的编辑
    public function coattredit(Request $request)
    {
        $data = request()->param();
        $coattr = new Coattr();
        $data['lang'] = $this->lang;
        if ($request->isGet()) {
            return view('coattr/coattrinfo', [
                'str' => 'coattredit',
                'id' => $data['id'],
            ]);
        } elseif ($request->isAjax() && $request->isPost() && isset($data['getcoattr'])) {
            //获取编辑的数据
            $wheremap['id'] = $data['id'];
            $info = getlanginfo('coattr', $wheremap);
            $coattr_select = Db::name('coattr_select')->field('id,option_text')->where('coattr_id', $info['id'])->select();
            //公司类型
            $where['a.lang'] = $data['langs'];//语言标志
            $join = [
                ['nt_cotype b', 'a.mkey=b.mkey']
            ];
            $table = 'multi_lang';
            //获取公司的类型
            $resdata = getmultidata($table, $join, $where)['data'];
            $info['coattr_select'] = $coattr_select;
            echo json_encode(array('info' => $info, 'cotypedata' => $resdata));
        } elseif ($request->isAjax() && $request->isPost() && $data['act'] == 'coattredit') {
            //编辑
            $coattrret = $coattr->addeditcoattr($data);
            $udata["status"] = $coattrret['status'];
            $udata['msg'] = $coattrret['msg'];
            echo json_encode($udata);
        }
    }

    //资料属性的删除
    public function coattrdelete(Request $request)
    {
        $coattr = new Coattr();
        $data = $request->param();
        $data['langs'] = $this->lang;
        if ($request->isPost() && $request->isAjax()) {
            $coattrret = $coattr->delcoattr($data, 1);
            $udata["status"] = $coattrret['status'];
            $udata['msg'] = $coattrret['msg'];
            echo json_encode($udata);
        }
    }

    //资料属性的清除
    public function coattrclear(Request $request)
    {
        $coattr = new Coattr();
        $data = $request->param();
        $data['langs'] = $this->lang;
        if ($request->isPost() && $request->isAjax()) {
            $coattrret = $coattr->delcoattr($data, 2);
            $udata["status"] = $coattrret['status'];
            $udata['msg'] = $coattrret['msg'];
            echo json_encode($udata);
        }
    }

    //客户列表
    public function customercompany(Request $request)
    {
        $res = $request->param();
        $res['lang'] = $this->lang;
        if ($request->isAjax() && $request->isPost()) {
            $company = new Company();
            $getcompany = $company->getcompany($res);
            //国家的显示
            $country = getables('country');
            if (isset($res['country_id']) && $res['country_id']) {
                $provinces = Db:: name('provinces')->where('country_id', $res['country_id'])->select();
            } else {
                $provinces = getables('provinces');
            }
            $join = [
                ['nt_cotype b', 'a.mkey=b.mkey']
            ];
            $table = 'multi_lang';
            $where['a.lang'] = 'zh';//语言标志
            $cotype = getmultidata($table, $join, $where)['data'];
            echo json_encode(array('getcompany' => $getcompany['data'], 'size' => $getcompany['count'], 'dataids' => $getcompany['ids'], 'country' => $country, 'provinces' => $provinces, 'cotype' => $cotype));
        } elseif ($request->isGet()) {
            return view('company/company');
        }
    }

    //处理客户的锁定与批量锁定
    public function companylock(Request $request)
    {
        $data = $request->param();
        $company = new Company();
        if ($request->isPost() && $request->isAjax()) {
            $companyret = $company->ulockadjustrecover($data);
            $udata["status"] = $companyret['status'];
            $udata['msg'] = $companyret['msg'];
            echo json_encode($udata);
        }
    }

    //处理客户的解锁
    public function companyunlock(Request $request)
    {
        $data = $request->param();
        $company = new Company();
        if ($request->isPost() && $request->isAjax()) {
            $companyret = $company->ulockadjustrecover($data);
            $udata["status"] = $companyret['status'];
            $udata['msg'] = $companyret['msg'];
            echo json_encode($udata);
        }
    }

    //处理客户的删除与批量删除（假删除）
    public function companydel(Request $request)
    {
        $data = $request->param();
        $company = new Company();
        if ($request->isPost() && $request->isAjax()) {
            $companyret = $company->ulockadjustrecover($data);
            $udata["status"] = $companyret['status'];
            $udata['msg'] = $companyret['msg'];
            echo json_encode($udata);
        }
    }

    //处理客户的删除与批量删除（真删除）
    public function companyclear(Request $request)
    {
        $data = $request->param();
        $company = new Company();
        if ($request->isPost() && $request->isAjax()) {
            $companyret = $company->ulockadjustrecover($data);
            $udata["status"] = $companyret['status'];
            $udata['msg'] = $companyret['msg'];
            echo json_encode($udata);
        }
    }

    //处理客户的恢复
    public function companyrecover(Request $request)
    {
        $data = $request->param();
        $company = new Company();
        if ($request->isPost() && $request->isAjax()) {
            $companyret = $company->ulockadjustrecover($data);
            $udata["status"] = $companyret['status'];
            $udata['msg'] = $companyret['msg'];
            echo json_encode($udata);
        }
    }

    //处理新客户的添加
    public function companyadd(Request $request)
    {
        $data = $request->param();
        $lang = $data['lang'] = $this->lang;
        $company = new Company();
        if ($request->isGet()) {
            return view('company/companyinfo', [
                'str' => 'companyadd',
                'country_id' => '',//国家id
                'company_id' => '',//公司id
            ]);
        } elseif ($request->isPost() && $request->isAjax() && isset($data['status'])) {
            //编辑点击不同的标签获取不同的数据
            $resdata = $company->getdetail($data);
            echo json_encode($resdata);
        } elseif ($request->isPost() && $request->isAjax() && $data['act'] == 'companyadd') {
            //新客户提交的接口
            $companyret = $company->addeditcompany($data);
            $udata["status"] = $companyret['status'];
            $udata['msg'] = $companyret['msg'];
            echo json_encode($udata);
        }
    }

    //处理新客户的编辑
    public function companyedit(Request $request)
    {
        $data = $request->param();
        $company = new Company();
        $lang = $data['lang'] = $this->lang;
        if ($request->isGet()) {
            $country_id = getValue('company', ['id' => $data['company_id']], 'country_id');
            return view('company/companyinfo', [
                'str' => 'companyedit',
                'company_id' => $data['company_id'],//公司id
                'country_id' => $country_id,//国家id
            ]);
        } elseif ($request->isPost() && $request->isAjax() && isset($data['status'])) {
            //编辑点击不同的标签获取不同的数据
            $resdata = $company->getdetail($data);
            echo json_encode($resdata);
        } elseif ($request->isPost() && $request->isAjax() && $data['act'] == 'companyedit') {
            //编辑提交后的数据接口
            $companyret = $company->addeditcompany($data);
            $udata["status"] = $companyret['status'];
            $udata['msg'] = $companyret['msg'];
            echo json_encode($udata);
        }
    }

    //公司的查看
    public function companycheck(Request $request)
    {
        $data = $request->param();
        $data['lang'] = $this->lang;
        $company = new Company();//公司模型
        $linkman = new Linkman();//联系人的模型
        $co_bank = new Co_bank();//公司账户
        $co_branch = new Co_branch();//分公司
        $co_evaluate = new Co_evaluate();//公司风评
        if ($request->isGet()) {
            $companydata = getinfo($data['company_id'], 'company', 'name,country_id');
            return view('company/companydetail', [
                'company_id' => $data['company_id'],//公司id
                'companyname' => $companydata['name'],//公司名称
                'country_id' => $companydata['country_id'],//国家id
            ]);
        } elseif ($request->isPost() && $request->isAjax() && isset($data['status'])) {
            $resdata = $company->getdetail($data);
            echo json_encode($resdata);
        } else if ($request->isPost() && $request->isAjax() && isset($data['getpro'])) {
            //采购订单合同详情
            $mappack['a.po_id'] = $data['id'];
            $buy_po_packdata = Db::name('buy_po_pack')->alias('a')->join('nt_buy_po_pack_remark b', 'a.id=b.po_pack_id', 'left')->field('a.*,b.content')->where($mappack)->select();
            foreach ($buy_po_packdata as $buy_po_packdatakey => $buy_po_packdataval) {
                $buy_po_packdata[$buy_po_packdatakey]['prodata'] = getProAndProchar($buy_po_packdataval, $data['lang'], 48);
                //获取每一个采购单价
                $mapplan['po_id'] = $data['id'];
                $mapplan['pro_id'] = $buy_po_packdataval['pro_id'];
                $mapplan['prochar_id'] = $buy_po_packdataval['prochar_id'];
                $mapplan['company_id'] = $data['company_id'];
                $buy_po_packdata[$buy_po_packdatakey]['price'] = getValue('buy_plan', $mapplan, 'price');
            }
            echo json_encode($buy_po_packdata);
        }elseif($request->isPost() && $request->isAjax() && isset($data['liaisondel'])){
            //联系人的删除
            $linkret = $linkman->dellink($data);
            echo json_encode($linkret);
        }elseif($request->isPost() && $request->isAjax() && isset($data['bankdel'])){
            //处理银行的删除
            $bankret = $co_bank->delbank($data);
            echo json_encode($bankret);
        }elseif($request->isPost() && $request->isAjax() && isset($data['branchdel'])){
            //处理分公司的删除
            $branchret = $co_branch->delbranch($data);
            echo json_encode($branchret);
        }elseif($request->isPost() && $request->isAjax() && isset($data['evaluatedel'])){
            //处理风评删除
            $evaluateret = $co_evaluate->delevaluate($data);
            echo json_encode($evaluateret);
        }elseif($request->isPost() && $request->isAjax() && isset($data['linkaddedit'])){
            //联系人的保存
            $linkret = $linkman->addeditlinkman($data);
            echo json_encode($linkret);
        }elseif($request->isPost() && $request->isAjax() && isset($data['bankaddedit'])){
            //银行的保存
            $bankret = $co_bank->addeditbank($data);
            echo json_encode($bankret);
        }elseif($request->isPost() && $request->isAjax() && isset($data['branchaddedit'])){
            //分公司保存
            $branchret = $co_branch->addeditbranch($data);
            echo json_encode($branchret);
        }elseif($request->isPost() && $request->isAjax() && isset($data['evaluateaddedit'])){
            //风评保存
            $evaluateret = $co_evaluate->addeditevaluate($data);
            echo json_encode($evaluateret);
        }
    }

    //处理销售资料调整
    public function companyadjust(Request $request)
    {
        $data = $request->param();
        $data['lang'] = $this->lang;
        if ($request->isPost() && $request->isAjax() && isset($data['adjust'])) {
            //销售资料中的调整
            $mapadjust['co_id'] = $data['company_id'];
            $mapadjust['branch_id'] = 0;
            $adjustinfo = Db::name('co_sale')->where($mapadjust)->find();
            if ($adjustinfo) {
                if ($adjustinfo['pledge'] == 1) {
                    $adjustinfo['pledge'] = true;
                } else {
                    $adjustinfo['pledge'] = false;
                }
                if ($adjustinfo['makefirst'] == 1) {
                    $adjustinfo['makefirst'] = true;
                } else {
                    $adjustinfo['makefirst'] = false;
                }
                if ($adjustinfo['credit4order'] > 0) {
                    $adjustinfo['update_date'] = getTimeDate($adjustinfo['update_at'], 15);
                }
                $adjustinfo['pay_type_ids'] = explode(',', $adjustinfo['pay_type_ids']);
            }
            //处理每一个付款方式的失败次数
            $failnum = Db::name('co_sale_fail')->where('co_id', $data['company_id'])->select();
            $one = $two = $three = $four = $five = $six = $seven = 0;//付款失败次数
            foreach ($failnum as $failnumkey => $failnumval) {
                if ($failnumval['pay_type_id']) {
                    switch ($failnumval['pay_type_id']) {
                        case '1':
                            $one = $failnumval['fail'];
                            break;
                        case '2':
                            $two = $failnumval['fail'];
                            break;
                        case '3':
                            $three = $failnumval['fail'];
                            break;
                        case '4':
                            $four = $failnumval['fail'];
                            break;
                        case '5':
                            $five = $failnumval['fail'];
                            break;
                        case '6':
                            $six = $failnumval['fail'];
                            break;
                        case '7':
                            $seven = $failnumval['fail'];
                            break;
                    }
                }
            }
            $arr = array('one' => $one, 'two' => $two, 'three' => $three, 'four' => $four, 'five' => $five, 'six' => $six, 'seven' => $seven);
            //管理员授权额度（该公司）
            $credit4admindata = getables('co_credit4admin', ['co_id' => $data['company_id']]);
            foreach ($credit4admindata as $credit4admindatakey => $credit4admindataval) {
                $credit4admindata[$credit4admindatakey]['adminname'] = getValue('admin', ['id' => $credit4admindataval['admin_id']], 'nickname');
                $credit4admindata[$credit4admindatakey]['update_date'] = getTimeDate($credit4admindataval['update_at'], 15);
            }
            echo json_encode(array(
                'adjustdata' => $adjustinfo,
                'numfail' => $arr,
                'credit4admindata' => $credit4admindata
            ));
        } else if ($request->isAjax() && $request->isPost() && isset($data['adjustsave'])) {
            if (!isset($data['delivery_id'])) {
                echo json_encode(array('msg' => '请选择送货类型', 'status' => 2));
                exit();
            }
            if (!isset($data['pay_type_ids'])) {
                echo json_encode(array('msg' => '请选择支付类型', 'status' => 2));
                exit();
            }
            if ($data['credit4admin']) {
                //管理员的授予额度的写入
                $mapadmin['co_id'] = $data['company_id'];
                $mapadmin['admin_id'] = session('userid');
                $adminco = Db::name('co_credit4admin')->where($mapadmin)->find();
                if ($adminco) {
                    //更新
                    Db::name('co_credit4admin')->where($mapadmin)->update([
                        'point' => $data['credit4admin'],
                        'update_at' => time(),
                    ]);
                } else {
                    //写入
                    $insertadmin['co_id'] = $data['company_id'];
                    $insertadmin['admin_id'] = session('userid');
                    $insertadmin['point'] = $data['credit4admin'];
                    $insertadmin['create_at'] = $insertadmin['update_at'] = time();
                    Db::name('co_credit4admin')->insert($insertadmin);
                }
            }

            //销售资料中调整的保存
            $mapsale['co_id'] = $data['company_id'];
            $mapsale['branch_id'] = 0;
            $info_cosale = Db::name('co_sale')->where($mapsale)->find();
            $pledge = $data['pledge'] == 'true' ? 1 : 0;
            $makefirst = $data['makefirst'] == 'true' ? 1 : 0;
            $co_credit4admin = Db::name('co_credit4admin')->where('co_id', $data['company_id'])->sum('point');//该公司管理员授权的总额度
            if ($info_cosale) {
                Db::name('co_sale')->where($mapsale)->update([
                    'delivery_id' => $data['delivery_id'],
                    'pay_type_ids' => implode(',', $data['pay_type_ids']),
                    'pledge' => $pledge,
                    'makefirst' => $makefirst,
                    'update_at' => time(),
                    'credit' => $co_credit4admin + $info_cosale['credit4order'],
                    'credit4admin' => $co_credit4admin,//管理员授权的额度
                ]);
            } else {
                $salecoinsert['co_id'] = $data['company_id'];
                $salecoinsert['delivery_id'] = $data['delivery_id'];
                $salecoinsert['pay_type_ids'] = implode(',', $data['pay_type_ids']);
                $salecoinsert['pledge'] = $pledge;
                $salecoinsert['makefirst'] = $makefirst;
                $salecoinsert['makefirst'] = $makefirst;
                $salecoinsert['credit'] = $co_credit4admin;
                $salecoinsert['credit4admin'] = $co_credit4admin;//管理员额度
                Db::name('co_sale')->insert($salecoinsert);
            }
            //对重新授权的支付方式，将失败次数清0
            $cofail = Db::name('co_sale_fail')->where('co_id', $data['company_id'])->select();
            foreach ($cofail as $cofailkey => $cofailval) {
                if (in_array($cofailval['pay_type_id'], $data['pay_type_ids'])) {
                    Db::name('co_sale_fail')->where(['co_id' => $data['company_id'], 'pay_type_id' => $cofailval['pay_type_id']])->update(['fail' => 0, 'update_at' => time()]);
                }
            }
            echo json_encode(array('msg' => '调整成功', 'status' => 1));
        }
    }

    //公司的批量调整
    public function batchcompany(Request $request)
    {
        $data = $request->param();
        $data['lang'] = $this->lang;
        $company = new Company();
        if ($request->isGet()) {
            return view('company/batchall');
        } else if ($request->isAjax() && $request->isPost() && isset($data['getbatch'])) {
            //获取批量调整后的数据
            $companydata = $company->getcompanydatas($data);
            echo json_encode(array('getcompany' => $companydata));
        } else if ($request->isAjax() && $request->isPost() && $data['act'] == 'batchadd') {
            //提交的数据
            $companyret = $company->batchall($data);
            $udata["status"] = $companyret['status'];
            $udata['msg'] = $companyret['msg'];
            echo json_encode($udata);
        }
    }
}
